package com.immunology.service.security.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.stereotype.Service;

import com.immunology.domain.Role;
import com.immunology.domain.User;
import com.immunology.exception.UserAlreadyExistException;
import com.immunology.service.RoleService;
import com.immunology.service.UserService;
import com.immunology.service.security.UserSecurityService;

@Service(value = "userSecurityService")
public class UserSecurityServiceImpl implements UserSecurityService {

	private static final Logger LOG = Logger
			.getLogger(UserSecurityServiceImpl.class);

	@Autowired
	private UserService userService;

	@Autowired
	private RoleService roleService;

	private static final int STRENGLT_256 = 256;

	@Override
	public void registerUser(User user) throws UserAlreadyExistException {
		String login = user.getLogin();
		System.out.println(user.getLogin());
		if (userService.getByLogin(login) == null) {
			user.setPassword(encodePassword(user.getPassword(), user.getLogin()));
			LOG.info("Adding security role for " + login);

			List<Role> roles = new ArrayList<Role>();
			roles.add(roleService.getAll().get(2));//2 - doctor
			user.setRoles(roles);
			userService.save(user);
		} else {
			throw new UserAlreadyExistException(
					"User already exists in DataBase");
		}
	}

	@Override
	public void updateUser(User user){
		user.setPassword(encodePassword(user.getPassword(), user.getLogin()));
		List<Role> roles = new ArrayList<Role>();
		roles.add(roleService.getAll().get(2));//2 - doctor
		user.setRoles(roles);
		userService.update(user);
	}
	
	private String encodePassword(String password, Object salt) {
		ShaPasswordEncoder encoder = new ShaPasswordEncoder(STRENGLT_256);
		password = encoder.encodePassword(password, salt);
		return password;
	}

}
